package cn.tx.dao.impl;

import cn.tx.dao.EmpDao;
import cn.tx.model.Emp;
import cn.tx.util.DBUtil;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class EmpDaoImpl implements EmpDao{


    @Override
    public void insert(Emp emp) {
        String sql="insert into emp( EMP_ID, ENAME , GENDER ,HIREDATE) values(null,?,?,?);";

        PreparedStatement stmt=null;
        try {
            //驱动加载
            stmt= DBUtil.getPrepareStatement(sql);
            stmt.setString(1,emp.getEname());
            stmt.setInt(2,emp.getGender());
            stmt.setDate(3,new Date(System.currentTimeMillis()));

            //执行SQL
            int i = stmt.executeUpdate();
            System.out.println("插入完毕"+i+"条");


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeRes(stmt);
        }
    }

    @Override
    public void update(Emp emp) {

        String sql="update emp t set t.ename=?,t.gender=?,t.hiredate=? where t.emp_id=?";

        PreparedStatement stmt=null;
        try {
            stmt=DBUtil.getPrepareStatement(sql);
            //驱动加载
            stmt.setString(1,emp.getEname());
            stmt.setInt(2,emp.getGender());
            stmt.setDate(3,new Date(System.currentTimeMillis()));

            stmt.setInt(4,emp.getEmpId());

            int i = stmt.executeUpdate();
            System.out.println("修改完毕"+i+"条");


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeRes(stmt);
        }

    }

    @Override
    public void delete(int empId) {

        String sql="delete from emp where emp_id=?;";


        PreparedStatement stmt=null;
        try {
            //驱动加载
            stmt=DBUtil.getPrepareStatement(sql);
            stmt.setInt(1,empId);
            stmt.executeUpdate();
            System.out.println("执行完毕");


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeRes(stmt);
        }

    }

    @Override
    public List<Emp> selectEmp() {
        List<Emp> emps=new ArrayList<Emp>();

        String sql="select * from emp ";


        PreparedStatement statement = DBUtil.getPrepareStatement(sql);
        ResultSet rs = null;
        try {
            rs = statement.executeQuery(sql);

            while(rs.next()){
                int empId = rs.getInt(1);
                String ename = rs.getString(2);
                int gender = rs.getInt(3);
                Date date = rs.getDate(4);

                Emp e=new Emp(empId,ename,gender,date);

                emps.add(e);



            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        System.out.println("执行完毕");
        DBUtil.closeRes(rs);

        return emps;
    }
}
